package com.qxp.simplerpc.proxy;

import com.qxp.simplerpc.config.ServerConfig;
import com.qxp.simplerpc.connect.RpcClientHandler;
import com.qxp.simplerpc.connect.RpcClientInvoker;
import com.qxp.simplerpc.entity.InvokerMessage;
import com.qxp.simplerpc.exception.RpcException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.*;

/**
 * @author qianxiaopeng
 */
@Component
public class CommonProxy extends AbstractProxy{
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private RpcClientHandler rpcClientHandler;
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private RpcClientInvoker rpcClientInvoker;
    @Override
    public <T> T getProxy(Class<?> cls, String className,String beanName) {
        throw new RpcException("not valid method");
    }

    @Override
    public <T> T getProxy(Class<?> cls) {
       return this.getProxy(cls,null,null);
    }


    protected Object connect(Class<?> cls, Method method, Object[] args, String className, String beanName)  {
        // class message instance
        InvokerMessage invokerMessage = new InvokerMessage();
        invokerMessage.setInterfaceI(cls);
        invokerMessage.setClassName(className);
        invokerMessage.setMethodName(method.getName());
        invokerMessage.setParameterTypes(method.getParameterTypes());
        invokerMessage.setArgs(args);
        invokerMessage.setToken(getToken());
        invokerMessage.setBeanName(beanName);
        invokerMessage.setClientHost(serverConfig.getLocalHost());
        invokerMessage.setClientPort(serverConfig.getServerPort());
        // 向服务器发送消息
        return  rpcClientInvoker.invoke(invokerMessage);
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    @Override
    public RpcClientHandler getRpcClientHandler() {
        return rpcClientHandler;
    }

    @Override
    public void setRpcClientHandler(RpcClientHandler rpcClientHandler) {
        this.rpcClientHandler = rpcClientHandler;
    }
}
